/*
Copyright 2010-2011 CumulusCloud
http://cumuluscloud.cc

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package appmanager.server.appstore.runner;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

import appmanager.shared.vo.Progress;

public class Runner {
	private static Logger logger = Logger.getLogger(Runner.class.getName());
	private static ArrayBlockingQueue<Downloader> list = new ArrayBlockingQueue<Downloader>(1000);
	private static ExecutorService exeserv = new ThreadPoolExecutor(1, 2, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<Runnable>(1000));
	
	public synchronized static void addRun(Downloader run) {
		cleanExpired();
		if (isAlreadyIn(run.getName())) {
			logger.info("Not adding since already running " + run.getName());
			return;
		}
		
		logger.info("Adding " + run.getName());
		list.add(run);
		exeserv.execute(run);
	}
	
	private synchronized static void cleanExpired() {
		long now = new Date().getTime();
		
		Iterator<Downloader> it = list.iterator();
		while (it.hasNext()) {
			Downloader next = it.next();
			long end = next.getEnd();
			if (end == -1) continue;
			
			if ((now-end) > 60000) {
				logger.info("Remove expired " + next.getName());
				it.remove();
			}
		}
	}
	
	public synchronized static List<Progress> getProgresses() {
		cleanExpired();
		List<Progress> result = new ArrayList<Progress>();
		for (Downloader next: list) {
			Progress p = new Progress();
			p.setName(next.getName());
			p.setProgress(next.getProgress());
			p.setCompleted(next.getEnd() != -1);
			p.setStatus(next.getStatus());
			result.add(p);
		}
		return result;
	}
	
	public synchronized static boolean isAlreadyIn(String name) {
		for (Downloader next: list) {
			if (next.getName().equals(name)) return true;
		}
		
		return false;
	}
}
